<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PageQuery } from '#/api/common';

import { useVbenDrawer } from '@vben/common-ui';

import { useDebounceFn } from '@vueuse/core';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { bindDevice } from '#/api/iot/device/group';
import { devicetList } from '#/api/iot/device/manage';
import { getProductList } from '#/api/iot/product';

import { columns, querySchema } from './drawerData';

const emit = defineEmits<{ reload: [] }>();

const formOptions: VbenFormProps = {
  schema: querySchema(),
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  handleReset: async () => {
    // selectDeptId.value = [];

    const { formApi, reload } = tableApi;
    await formApi.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.userId !== 1,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const res = await devicetList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return res;
      },
    },
  },
  headerCellConfig: {
    height: 44,
  },
  cellConfig: {
    height: 48,
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'bind-device-drawer',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const initFormData = async (val?: string) => {
  const params: PageQuery = {};
  if (val) {
    params.productName = val;
  }
  const res = await getProductList(params);
  const options = res.rows || [];

  // 产品信息
  tableApi.formApi.updateSchema([
    {
      componentProps: {
        fieldNames: { label: 'productName', value: 'id' },
        options,
        showSearch: true,
        filterOption: false,
        onSearch: useDebounceFn(async (val: string) => {
          initFormData(val);
        }, 300),
      },
      fieldName: 'productId',
    },
  ]);
};

const [BasicDrawer, drawerApi] = useVbenDrawer({
  onConfirm: handleConfirm,
  onOpened: initFormData,
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const deviceIds =
      tableApi.grid
        .getCheckboxRecords()
        .map((item) => item.id)
        .join(',') || '';
    const deviceGroupId = sessionStorage.getItem('selectDeptId') || undefined;
    await bindDevice({
      deviceGroupId,
      deviceIds,
    });
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}
</script>

<template>
  <BasicDrawer title="绑定设备" class="w-[1000px]">
    <BasicTable />
  </BasicDrawer>
</template>
